import { defineStore } from "pinia";
import type { UserAddressStore } from "./interface/pay";

export const userPayStore = defineStore("pay", {
  state: (): UserAddressStore => {
    return {
      userAddress: JSON.parse(localStorage.getItem("userAddress") || "[]"), // 收件人信息
      // userAddress: [], // 收件人信息
    };
  },
  // 只读的计算属性数据
  getters: {
    // 当前收件人
    userSelect(state) {
      return state.userAddress.find((item) => item.isSelected) || {};
    },
  },
  // 所有更新都在action中完成
  actions: {
    // 添加收件人
    add(addressInfo) {
      // console.log(addressInfo);
      this.userAddress.push(addressInfo);
      // 选中当前项
      this.isCheck(this.userAddress.length - 1);
      // 缓存收件人信息
      localStorage.setItem("userAddress", JSON.stringify(this.userAddress));
    },
    // 选择
    isCheck(ind: number) {
      this.userAddress.forEach((item, index) => {
        item.isSelected = ind === index;
        // console.log(item.isSelected);
      });
      // console.log(this.userAddress);
    },
  },
  // pinia移除了mutation:{}
});
